package com.epam.qanda.web.servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.Category;
import com.epam.qanda.db.service.CategoryService;

public class CategoryListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendRedirect("");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String path = request.getServletPath();
		if (path.equals("/removeCategory")) {
			int categoryId = Integer.parseInt(request.getParameter("cId").trim());
			new CategoryService().delete(categoryId);
			return;
		} else if (path.equals("/addCategory")) {

			Category category = new Category();
			String cName = request.getParameter("cName").trim();
			request.removeAttribute("cName");
			request.setAttribute("cName", cName);
			category.setName(cName);
			category.setName(category.getName().replaceAll("'", "&rsquo;"));
			category.setName(category.getName().replaceAll("\"", "&quot;"));
			try {
				new CategoryService().create(category);
				request.setAttribute("result", "added");
			} catch (RuntimeException e) {
				LOG.warn(e.getMessage());
				request.setAttribute("result", "exist");
			}
		}
		request.getRequestDispatcher("").forward(request, response);
	}
}
